import * as umfToast from '../../../../../utils/UmfToast';
import * as regexUtils from '../../../../../utils/RegexUtils';
import { $Toptips } from '../../../../../components/CompRouter';
const constants = require('../../../../../common/Constants.js');
const imPayCommon = {
  /**
       * 添加更多点击事件
       */
  addMore: function () {
    let codeList = this.data.qrCodeList.concat([]);//透传，防止codeList变导致this.data.qrCodeList变
    codeList.push({ index: codeList.length, code: '', active: true });
    this.setData({
      qrCodeList: codeList
    });
  },

  /**
     * code输入框监听
     * @param e
     */
  codeInput: function (e) {
    let index = e.currentTarget.id;
    let value = e.detail.value.trim();

    this.data.qrCodeList[index].code = value;
    this.setData({
      qrCodeList: this.data.qrCodeList
    });
    if(this.data.pageInPos){
      this._pageCacheStorage({ 'qrCodeList': JSON.stringify(this.data.qrCodeList), 'qrCodeListSubmit': this.RemoveDuplicate(this.convertCodeList(this.data.qrCodeList)) });
      // this._pageCacheStorage({ });
    }
    
  },

  /**
     * 扫码识别收款码
     */
  scanCode: function (e) {
    let scanIndex = e.currentTarget.id;
    let arr = this.data.qrCodeList;
    wx.scanCode({
      success: (res) => {
        let code = res.result.substring(res.result.indexOf("qr_code=") + 8).trim();

        let codeList = this.convertCodeList(arr);
        if (codeList.indexOf(code) >= 0) {
          umfToast.showToast("该收款码已添加！");
          return;
        }

        arr[scanIndex].code = code;
        this.setData({
          qrCodeList: arr
        })
      },
      fail: function (res) {
      }
    })
  },
  /**
 * 提取qrCodeList中的code
 */
  convertCodeList(qrCodeList) {
    let helpers = {
      filterCode: (item) => {
        return item.active && item.code;
      },

      getCodes: (item) => {
        return item.code;
      }
    };
return qrCodeList.filter(helpers.filterCode).map(helpers.getCodes);
},

/**
 * 去掉重复的数据
 * @param list
 * @constructor
 * @return {Array}
 */
RemoveDuplicate(list) {
  if (!list) {
    return [];
  }
  let filter = function (element, index, self) {
    return self.indexOf(element) === index;
  };
  return list.filter(filter);
},
/**
   * 校验
   */
_imCheckForm(wechatRate, alipayRate) {
  let values = [
    [wechatRate, constants.RegexTypes.RATE_CHECK],
    [alipayRate, constants.RegexTypes.RATE_CHECK]
  ];
  let errorMsg = regexUtils.regexTypesWithMsg(values);
  if (errorMsg) {
    return errorMsg;
  }

  for (let index = 0; index < this.data.qrCodeList.length; index++) {
    if (this.data.qrCodeList[index].code && this.data.qrCodeList[index].code.length !== 8) {
      // $Toptips.error({ text: "付款码应为8位数字" });
      return "付款码应为8位数字";
    }
  }
  return '';
},

}

export default imPayCommon;